import express from "express";
import Result from "../../common/result.js";
import { spawn } from "node:child_process";
import { PYTHON_PATH, taskList } from "../../const/index.js";
import { fileURLToPath } from "node:url";
import { getRelativePercent } from "../../utils/number.js";
import { nanoid } from "nanoid";

const ttsRouter = express.Router();

const ttsScript = fileURLToPath(
  new URL("../../python/other/edge-tts.py", import.meta.url)
);

ttsRouter.post("/textToSpeech", async (req, res) => {
  const { text, voice, speechSpeed, intonation } = req.body;
  if (!text) {
    return res.send(Result.error("Text is required.", "文本不能为空.", 400));
  }
  try {
    const taskId = nanoid();
    const process = spawn(PYTHON_PATH, [
      ttsScript,
      text,
      voice,
      getRelativePercent(speechSpeed),
      getRelativePercent(intonation),
      taskId,
    ]);
    taskList.set(taskId, {
      fileHash: taskId,
      fileType: "folder",
      fileNmae: taskId,
      done: false,
    });
    process.on("close", () => {
      taskList.get(taskId).done = true;
    });
    return res.send(Result.success({ taskId }, "任务正在进行中"));
  } catch (err) {
    return res.send(Result.error(err, "语音合成失败.", 500));
  }
});

export default ttsRouter;
